from flask import abort, jsonify
from flask import current_app
from flask import g
from flask import render_template
from flask import request

from Info.utils.common import get_user_info
from Info import db
from Info.constants import CLICK_RANK_MAX_NEWS
from Info.models import News, Comment, CommentLike
from Info.utils.response_code import RET
from . import news_blu


# 评论点赞
@news_blu.route('/comment_like',methods=['POST'])
@get_user_info
def comment_like():
    # １．接受参数
    user = g.user
    req_dic = request.json
    news_id= req_dic.get("news_id")
    comment_id=req_dic.get("comment_id")
    action = req_dic.get("action")
    # ２．检验参数
    if not user:
        return jsonify(errno=RET.USERERR, errmsg='用户为登陆，不能点赞评论')

    if not all([news_id,comment_id,action]):
        return jsonify(errno=RET.DATAERR, errmsg='缺少参数')

    if action not in ('add','remove'):
        return jsonify(errno=RET.DATAERR, errmsg='action参数错误')

    # 检查数据库评论表是否有该条评论，因为需要往该评论增加点赞人数
    try :
        com= Comment.query.get(comment_id)
    except Exception as e:
        return jsonify(errno=RET.DATAERR, errmsg='该评论不存在数据中')

    # comment_like = CommentLike.query.filter_by(CommentLike.comment_id=comment_id,)
    comment_like = CommentLike.query.filter_by(comment_id=comment_id, user_id=user.id).first()
    if action == 'add':
        if not  comment_like:
            comment_like= CommentLike()
            comment_like.comment_id = comment_id
            comment_like.user_id = user.id
            db.session.add(comment_like)
            com.like_count += 1
    else:
    #     取消点赞
        com.like_count -= 1
        comment_like = CommentLike.query.filter_by(comment_id=comment_id, user_id=user.id).first()
        db.session.delete(comment_like)
    try:
        db.session.commit()
    except Exception as e :
        return  jsonify(errno=RET.DBERR,errmsg='点赞数据添加数据库失败')

    return jsonify(errno=RET.OK,errmsg='评论点赞成功',like_count= com.like_count)

# 新闻评论
@news_blu.route('/news_comment',methods=['POST'])
@get_user_info
def news_comment():
    # news_id int 新闻id
    # comment string  评论内容
    # parent_id int    否 回复的评论的id
    # 获取参数
    req_dict =  request.json
    news_id = req_dict.get('news_id')
    comment_str = req_dict.get('comment')
    parent_id = req_dict.get('parent_id')
    user = g.user
    # 验证参数
    # 如果用户没有登陆，不能发表评论
    if not user :
        return jsonify(errno=RET.USERERR,errmsg='您还没登陆，不能发表评论')
    # 如果没有该条新闻则不能发表评论
    if not all([news_id,comment_str]):
        return jsonify(errno=RET.DATAERR,errmsg='参数错误')
    try:
        news_id = int(news_id)
        if parent_id:
            parent_id = int(parent_id)
    except Exception as e :
        return jsonify(errno=RET.DATAERR,errmsg='参数转换为整型错误')

    try:
        news = News.query.get(news_id)
    except Exception as e:
        return jsonify(errno=RET.DATAERR,errmsg='查询新闻数据失败')

    if not news:
        return jsonify(errno=RET.DATAERR,errmsg='该新闻数据不存在')

    #将评论内容添加到数据库中
    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news_id
    comment.content = comment_str

    if parent_id:
        comment.parent_id = parent_id
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        return jsonify(errno=RET.DATAERR,errmsg='评论内容保存失败')
    comment1 =comment.to_dict()
    return jsonify(errno=RET.OK,errmsg='评论成功',comment=comment.to_dict())


# 新闻收藏
@news_blu.route('/news_collect',methods=['POST'])
@get_user_info
def news_collect():
    # 获取参数
    user = g.user
    req_dic = request.json
    news_id = req_dic.get('news_id')
    action = req_dic.get('action')

    # 检查用户是否已经登陆
    if not user:
        return jsonify(errno=RET.USERERR,errmsg='用户未登陆，无法收藏新闻')
    # 检查接受的前端参数
    if not all([news_id,action]):
        return jsonify(errno=RET.DATAERR,errmsg='参数错误')
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='查询新闻数据失败')

    if not news :
        return jsonify(errno=RET.NODATA,errmsg='没有该新闻数据')

    if action == "collect":
        if news not in user.collection_news:
            user.collection_news.append(news)
        else:
            return jsonify(errno=RET.PARAMERR, errmsg='您已经关注')
    else:
        user.collection_news.remove(news)
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存失败")

    return jsonify(errno=RET.OK,errmsg='成功退出')


# 新闻详情
@news_blu.route('/<int:news_id>')
@get_user_info
def news(news_id):
    # 排行获取点击数据
    new_list = News.query.order_by(News.clicks.desc()).limit(CLICK_RANK_MAX_NEWS)
    click_new_list = []
    for new in new_list:
        click_new_list.append(new)
    # 获取新闻详情
    news = News.query.get(news_id)
    if not news :
        abort(404)
    news.clicks += 1
    db.session.commit()

    # 获取用户信息
    user = g.user

    # 从数据库中读取评论数据
    try:
        comments = Comment.query.filter(Comment.news_id==news_id)
        # comments = Comment.query.filter(Comment.news_id==news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        return jsonify(errno=RET.DATAERR,errmsg='获取评论失败')
    comment_list =[]
    for comment in comments:
        comment_list.append(comment.to_dict())
    # 收藏新闻
    # 判断是否收藏该新闻，默认值为 false
    is_collected = False
    # 判断用户是否收藏过该新闻

    if g.user:
        if news in g.user.collection_news:
            is_collected = True
    #获取点赞

    return  render_template('news/detail.html',
                            new_list=new_list,
                            news=news,
                            user=user,
                            is_collected=is_collected,
                            comment_list=comment_list)
